"""
健康检查路由
用于监控系统运行状态和检测问题
"""
from flask import Blueprint, jsonify
from app import db
from sqlalchemy import text
import sys

health_bp = Blueprint('health', __name__)

@health_bp.route('/health')
def health_check():
    """基本健康检查"""
    return jsonify({
        'status': 'healthy',
        'message': '系统运行正常'
    })

@health_bp.route('/health/detailed')
def detailed_health_check():
    """详细健康检查"""
    status = {
        'status': 'healthy',
        'checks': {}
    }
    
    # 检查数据库连接
    try:
        db.session.execute(text('SELECT 1'))
        status['checks']['database'] = {
            'status': 'healthy',
            'message': '数据库连接正常'
        }
    except Exception as e:
        status['status'] = 'unhealthy'
        status['checks']['database'] = {
            'status': 'unhealthy',
            'message': f'数据库连接失败: {str(e)}'
        }
    
    # 检查关键表是否存在
    required_tables = [
        'user', 'project', 'project_task', 'customer', 
        'notification', 'user_activity', 'follow_up',
        'project_milestone'
    ]
    
    missing_tables = []
    for table in required_tables:
        try:
            db.session.execute(text(f'SELECT 1 FROM {table} LIMIT 1'))
        except Exception:
            missing_tables.append(table)
    
    if missing_tables:
        status['status'] = 'unhealthy'
        status['checks']['tables'] = {
            'status': 'unhealthy',
            'message': f'缺少表: {", ".join(missing_tables)}'
        }
    else:
        status['checks']['tables'] = {
            'status': 'healthy',
            'message': '所有必需表都存在'
        }
    
    # 检查关键列是否存在
    column_issues = []
    
    # 检查user表的updated_at列
    try:
        db.session.execute(text('SELECT updated_at FROM user LIMIT 1'))
    except Exception:
        column_issues.append('user表缺少updated_at列')
    
    # 检查notification表的updated_at列
    try:
        db.session.execute(text('SELECT updated_at FROM notification LIMIT 1'))
    except Exception:
        column_issues.append('notification表缺少updated_at列')
    
    if column_issues:
        status['status'] = 'unhealthy'
        status['checks']['columns'] = {
            'status': 'unhealthy',
            'message': '; '.join(column_issues)
        }
    else:
        status['checks']['columns'] = {
            'status': 'healthy',
            'message': '所有必需列都存在'
        }
    
    return jsonify(status)